﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using eTerm.PlugIn.NCore;
using eTerm.MsSql.DbProvider;
using SubSonic.Query;
using System.Net.Mail;

namespace eTerm.agencyERP.PlugIns
{
    public class TicketNoSyncPlugIn:BasePlugIn,IPlugIn
    {
        public override string PlugInName
        {
            get { return @"老头子系统票号状态比较插件"; }
        }



        protected override void ExecutePlugIn()
        {
            PnrDetr.All().Where(l => (l.StatusId & (int)DetrStatus.BEFORECOMPARE) != 0)
                 .Join(VErpTicketNo.All(), l => l.TicketNo, r => r.TicketNo, (l, r) => new { l, r.TicketNo, r.TradeType,r.Id })
                 .Join(VErpTicketNo.All().GroupBy(l=> l.TicketNo ,(KeyID,Items)=>new {KeyID, ID = Items.Max(y=>y.Id) }),l=>l.Id,r=>r.ID,(l,r)=>new { l.l,l.TicketNo,l.TradeType })
                 .ToList().ForEach(l => {
                     PnrHistory model = new PnrHistory() { TicketNoId = l.l.Id, ProcessDate = DateTime.Now, SourceStatusId=l.l.StatusId };
                     l.l.SetIsLoaded(true);
                     l.l.SetIsNew(false);
                     if (l.TradeType != @"退票")
                     {
                         l.l.StatusId =  (int)DetrStatus.COMPARERROR;
                         FireOnNotify(l.TicketNo, EventType.WARNING, string.Format(@"票号 {0} 被异常退票。", l.TicketNo));
                     }
                     else {
                         l.l.StatusId =  (int)DetrStatus.AFTERCOMPARE;
                         FireOnNotify(l.TicketNo, EventType.WARNING, string.Format(@"票号 {0} 正常退票。", l.TicketNo));
                     }
                     model.NewStatusId = l.l.StatusId;
                     model.Save();
                     l.l.ProcessDate = DateTime.Now;
                     l.l.Save();
                 });
        }


    }
}
